package com.zjxfood.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.BitmapUtils;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.alipay.PayResult;
import com.zjxfood.alipay.SignUtils;
import com.zjxfood.application.ExitApplication;
import com.zjxfood.common.Constants;
import com.zjxfood.view.RoundImageView;
import com.zjxfood.view.TiltTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

/**
 * 支付宝
 * @author zjx
 *
 */
public class JHAlipayActivity extends AppActivity implements OnClickListener {

	private Button mPayBtn;
	private PopupWindow mPopupWindow;//弹窗
	private LinearLayout mAlertLayout;
//	private ImageView mCancelX;
//	private Button mGrabRedBtn;
	private RelativeLayout mHeadLayout;
	private ImageView mBackImage;//返回
	private int successFlag=0;//成功标识符
	private String orderid;//订单id
	private Bundle mBundle;
	private String price,merchantName,mId;//价格、商家名字、用户id
	private TextView mPriceText;
	private String mLoginImagePath;//图片路径
	private RoundImageView mRoundImageView;
	private Bitmap mBitmap;
	private String mFlum;//返利
	private TiltTextView mFlumText;
	private TextView mMerchantName;
	private String callBackUrl = "http://api.zjxssnn.com/api/Payment/UserJhAlipayCallBack";//支付宝激活回调地址
	private BitmapUtils mBitmapUtils;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.alipay_pay_layout);
		setImmerseLayout(findViewById(R.id.head_layout));
		mBitmapUtils = new BitmapUtils(getApplicationContext());
		mBitmapUtils.configDefaultLoadFailedImage(R.drawable.log);
		ExitApplication.getInstance().addActivity(this);
		ExitApplication.getInstance().addJhActivity(this);
		mBundle = getIntent().getExtras();
		if(mBundle!=null){
			price = mBundle.getString("price");
			merchantName = mBundle.getString("merchantName");
			mId = mBundle.getString("mId");
			mLoginImagePath = mBundle.getString("LoginImage");
			mFlum = mBundle.getString("flum");
		}
		init();
		mPriceText.setText("￥"+price);
		mFlumText.setText("返利"+mFlum+"%");
		mMerchantName.setText(merchantName);
//		new Thread(imageRun).start();
//		ImageLoader.getInstance().displayImage(mLoginImagePath, mRoundImageView, options);
		mBitmapUtils.display(mRoundImageView, mLoginImagePath);
	}

	private void init() {
		mPayBtn = (Button) findViewById(R.id.alipay_pay_btn);
		mAlertLayout = (LinearLayout) findViewById(R.id.alipay_pay_alert_view);
		mHeadLayout = (RelativeLayout) findViewById(R.id.title_alipay_pay_id);
		mBackImage = (ImageView) mHeadLayout
				.findViewById(R.id.alipay_back_info_image);
		mPriceText = (TextView) findViewById(R.id.alipay_pay_money_text);
		mRoundImageView = (RoundImageView) findViewById(R.id.alipay_pay_round_image);
		mFlumText = (TiltTextView) findViewById(R.id.alipay_reabte_text);
		mMerchantName = (TextView) findViewById(R.id.alipay_pay_name_text);

		 mPayBtn.setOnClickListener(this);
		mBackImage.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.alipay_pay_btn:
			if(Constants.mId!=null && !(Constants.mId.equals(""))){
				pay();
			}else{
				Toast.makeText(getApplicationContext(), "支付失败,请重新登录！", Toast.LENGTH_SHORT).show();
			}
			
			break;

		case R.id.alipay_back_info_image:
			finish();
			// pay();
			break;
		}
	}

	// 抢红包
//	android.view.View.OnClickListener mGrabRedClick = new OnClickListener() {
//		@Override
//		public void onClick(View arg0) {
//			Intent intent = new Intent();
//			intent.setClass(getApplicationContext(), GrabRedActivity.class);
//			startActivity(intent);
//			mPopupWindow.dismiss();
//			mHandler.sendEmptyMessageDelayed(3, 0);
//		}
//	};

	OnClickListener mClickListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			mPopupWindow.dismiss();
			mHandler.sendEmptyMessageDelayed(3, 0);
		}
	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
			break;
		default:
			break;
		}
		return false;
	};

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constants.SDK_PAY_FLAG: {
				Log.i("zfbpay", "==========支付成功2========");
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
//					Toast.makeText(AlipayActivity.this, "支付成功",
//							Toast.LENGTH_SHORT).show();
					successFlag = 1;
					mHandler.sendEmptyMessageDelayed(4, 0);
					
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						successFlag = 0;
						Toast.makeText(JHAlipayActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();
					} else {
						successFlag = 0;
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(JHAlipayActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			case Constants.SDK_CHECK_FLAG: {
				Toast.makeText(JHAlipayActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			case 3:
				mAlertLayout.setVisibility(View.GONE);
				break;
			case 4:
				/*new Thread(payRun).start();*/

				Intent intentjh = new Intent();
				intentjh.setClass(getApplicationContext(), ActivationResultActivity.class);
				Bundle bundlejh = new Bundle();
				bundlejh.putString("result", "success");
				bundlejh.putString("zffs", "zfb");
				intentjh.putExtras(bundlejh);
				startActivity(intentjh);
				finish();
				break;
			case 5:
				//支付成功跳转到订单详情界面
				Date date = new Date(System.currentTimeMillis());
				SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss ");
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), OrderInfoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("Merchantname", merchantName);
				bundle.putString("Money", price);
				bundle.putString("Createtime", formatter.format(date));
				bundle.putString("Flnum", mFlum);
				bundle.putString("Logoimage", mLoginImagePath);
				bundle.putString("Payid", CheckOutActivity.orderId);
				bundle.putString("flag", 2+"");
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
				break;
			}

		};
	};
	
	//生成后台订单
//	Runnable payRun = new Runnable() {
//		
//		@Override
//		public void run() {
//			String str = "userid="+Constants.mId+"&mid="+mId+"&money="+price+"&payid="+CheckOutActivity.orderId+"&issuccess="+successFlag+"&zffs=zfb";			
//			try {
//				String res = ReadJson.getJson(Constants.getPay, str);
//				if(res.equals("1")){
//					mHandler.sendEmptyMessageDelayed(5, 0);
//				}else{
//					Toast.makeText(getApplicationContext(), "订单生成失败！", Toast.LENGTH_SHORT).show();
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//	};
	
//
	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay() {
		// 订单
		String orderInfo = getOrderInfo("[食尚男女]"+merchantName, merchantName, price);
		
		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(JHAlipayActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = Constants.SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {
			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(JHAlipayActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = Constants.SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + Constants.PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + Constants.SELLER + "\"";
		orderid = getJhOrderId();
		Log.i("merhcant", orderid+"===========支付宝========");
		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + orderid + "\"";
		
		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + callBackUrl
				+ "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
//		key = key +"-"+Constants.mId;
		key = key.substring(6, 15);
		return key+"-"+Constants.mId;
	}
	
	//生成订单
	public String getJhOrderId() {
		String str = System.currentTimeMillis()+"";
		String key = str.substring(3, 12);
		//时间戳+uid
		return key+"-"+Constants.mId;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, Constants.RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}
	
	Runnable imageRun = new Runnable() {
		
		@Override
		public void run() {
//			mBitmap = Constants.getHttpBitmap4(mLoginImagePath);
//			handler.sendEmptyMessageDelayed(1, 0);
		}
	};
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
//				mRoundImageView.setImageBitmap(mBitmap);
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onDestroy() {
		System.gc();
		super.onDestroy();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}
}
